package com.cssw.fyzb.busi.api.user;

import com.alibaba.fastjson.JSONObject;
import com.cssw.fyzb.busi.service.user.UserService;
import com.cssw.fyzb.busi.service.user.UserSourceService;
import com.cssw.fyzb.busi.util.AuthUtil;
import com.cssw.fyzb.busi.util.CodeUtil;
import com.cssw.fyzb.core.model.dodb.User;
import com.cssw.fyzb.core.model.dodb.UserSource;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import com.ydn.simplecache.SimpleCache;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

import static com.cssw.fyzb.busi.cache.CacheKeys.forRegister;
import static com.cssw.fyzb.busi.util.Bizs.*;

/**
 * 新增用户
 *
 * @author Feng Chen
 */
@Function(description = "微信登录参数", parameters = {
        @Parameter(name = "code", type = Type.String, description = "openid", required = true),
        @Parameter(name = "mobile", type = Type.String, description = "用户手机号", required = true),
        @Parameter(name = "verifyCode", type = Type.String, description = "手机验证码", required = true),
        @Parameter(name = "inviteCode", type = Type.String, description = "邀请码", required = true)
})
@Component
public class LoginByWechat implements Action {

    @Autowired
    private UserService userService;

    @Autowired
    private UserSourceService userSourceService;

    @Autowired
    private SimpleCache simpleCache;

    @Override
    public Response execute(Request request) throws Exception {
//        String appId = "932sj92ksjjfkalj";
//        String secret = "0x892hsi923jjsmma";
//        String code = request.getString("code");
//        String grantType = "authorization_code";
//        String urlFormat = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=%s";
//        String url = String.format(urlFormat, appId, secret, code, grantType);
//        System.out.println(url);
//        // 创建HttpClient实例
//        HttpClient client =  HttpClientBuilder.create().build();
//        // 根据URL创建HttpGet实例
//        HttpGet get = new HttpGet(url);
//        // 执行get请求，得到返回体
//        HttpResponse response = client.execute(get);
//        // 判断是否正常返回
//        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//            // 解析数据
//            String data = EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
//            System.out.println(data);
//        }

        try {
            String code = request.getString("code");
            //通过第一步获得的code获取微信授权信息
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AuthUtil.APPID + "&secret="
                    + AuthUtil.APPSECRET + "&code=" + code + "&grant_type=authorization_code";
            JSONObject jsonObject = AuthUtil.doGetJson(url);
            String openid = jsonObject.getString("openid");
            String token = jsonObject.getString("access_token");
            String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + openid
                    + "&lang=zh_CN";
            JSONObject userInfo = AuthUtil.doGetJson(infoUrl);

            //成功获取授权,以下部分为业务逻辑处理了，根据个人业务需求写就可以了
            if (userInfo != null && openid != null) {
                String nickName = userInfo.getString("nickName");
                String avatar = userInfo.getString("headimgurl");
                avatar = avatar.replace("\\", "");
                String userName = request.getString("userName");
                String province = request.getString("province");
                String city = request.getString("city");
                String sex = request.getString("sex");
                String inviteCode = request.getString("inviteCode");
                String mobile = request.getString("mobile");
                String verifyCode = request.getString("verifyCode");
                String cached = simpleCache.get(forRegister(mobile));
                //根据openid查询时候有用户信息
                // 校验验证码
                if (!verifyCode.equals(cached)) {
                    return Response.fail(ERROR_VERIFY.message, ERROR_VERIFY.code);
                }
                //推荐码
                User inviter = null;
                Long supUserId = null;
                if (StringUtils.isNotEmpty(inviteCode)) {
                    supUserId = CodeUtil.decode(inviteCode);
                    inviter = userService.getById(supUserId);
                    if (inviter == null) {
                        return Response.fail(ERROR_INVITCODE.message, ERROR_INVITCODE.code);
                    }
                }
                //判断手机号是否已经被绑定
                if (userService.getByMobile(mobile) != null) {
                    return Response.fail(ERROR_REGISTERED.message, ERROR_REGISTERED.code);
                }
                UserSource userSource = userSourceService.getBySourceCode(openid);
                if (Objects.isNull(userSource)) {
                    // 没有绑定用户请前往绑定
                    // 保存用户
                    Long userId = userService.saveWechat(supUserId, mobile, openid, userName, nickName, province, city, sex, avatar);
                    return Response.success("登录成功").put("userId", userId);
                } else {
                    // 已经绑定用户信息直接登录
                    return Response.success().put("userId", userSource.getUserId());
                }
            } else {
                return Response.fail("用户登录失败");
            }
        } catch (Exception e) {
            return Response.fail("用户登录失败");
        }
    }
}
